
package com.dkm.modules.sys.menu.service.impl;

import com.dkm.exception.ServiceException;
import com.dkm.modules.sys.menu.mapper.MenuMapper;
import com.dkm.modules.sys.menu.mapper.RoleMenuMapper;
import com.dkm.modules.sys.menu.service.MenuService;
import com.dkm.modules.sys.menu.service.RoleMenuService;
import com.dkm.modules.sys.role.model.RoleMenuPO;
import com.dkm.modules.sys.role.model.request.RoleMenuRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @ClassName RoleMenuServiceImpl
 * @Description: 角色菜单实现类
 * @Author yangbin
 * @Date 2019-09-17 23:47
 * @Version V1.0
 **/
@Slf4j
@Service
public class RoleMenuServiceImpl implements RoleMenuService {

    @Autowired
    private RoleMenuMapper roleMenuMapper;
    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    MenuService menuService;

    @Autowired
    MenuCacheService menuCacheService;

    @Override
    public void insertOrUpdate(RoleMenuRequest roleMenus) {
        Integer roleCode = roleMenus.getRoleCode();
        if (Objects.isNull(roleCode)) {
            throw new ServiceException("角色code必传");
        }

        List<Integer> menuCodes = roleMenus.getMenuCodes();
        if (CollectionUtils.isEmpty(menuCodes)) {
            throw new ServiceException("菜单codes必传");
        }
        // 删除原来的关联关系
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("role_code", roleCode);
        roleMenuMapper.deleteByMap(hashMap);

        // 重新插入
        for (Integer code : menuCodes) {
            RoleMenuPO menuPO = RoleMenuPO.builder()
                    .roleCode(roleCode)
                    .menuCode(code)
                    .build();
            roleMenuMapper.insert(menuPO);
        }

        // 清空缓存
        menuCacheService.delAllMenuAndBtnCache();
    }

}